<script setup lang="ts">
defineOptions({ name: 'VipSelectTable' })

interface Props {
  modelValue?: any
  props?: { label: string; value: string }
  size?: string
  placeholder?: string
  multiple?: boolean
  clearable?: boolean
  collapseTags?: boolean
  collapseTagsTooltip?: boolean
  filterable?: boolean
  disabled?: boolean
  // filterMethod?: Function
  // visibleChange?: Function
  tableWidth?: number
  tableHeight?: number
  border?: boolean
  tableData?: any[]
  pagination?: boolean
  total?: number
  pageSize?: number
  currentPage?: number
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  props: () => {
    return { label: 'label', value: 'value' }
  },
  size: 'default',
  placeholder: '请选择',
  multiple: false,
  clearable: false,
  collapseTags: false,
  collapseTagsTooltip: false,
  filterable: false,
  disabled: false,
  tableWidth: 800,
  border: true,
  pagination: false,
  total: 0,
  pageSize: 10,
  currentPage: 1
})
const emit = defineEmits(['page-change', 'update:modelValue', 'change'])
const onCurrentChange = (val: number) => {
  emit('page-change', val)
}
// const defaultValue = defineModel({ type: Array, default: () => [] })
// const defaultValue = defineModel({ type: Object | Array, default: () => null })
// const defaultValue = defineModel()
const defaultValue = ref<any[]>([])
const defaultSelect = ref<any[]>([])
const selectRef = ref()
const tableRef = ref()

// watch(
//   // defaultValue.value,
//   props.modelValue,
//   (newValue: any) => {
//     console.log('watch.defaultValue', newValue)
//     defaultValue.value = newValue
//     autoCurrentLabel()
//   },
//   { deep: true }
// )

// const { formItem } = useFormItem()

watch(
  () => props.modelValue,
  (newValue: any) => {
    console.log('watch.modelValue', newValue)
    autoCurrentLabel()
    // if (props.validateEvent) {
    // formItem?.validate('change').catch((err) => debugWarn(err))
    // }
  }
)

onMounted(() => {
  defaultValue.value = props.modelValue
  autoCurrentLabel()
  // setTableRowSelection()
})

//表格显示隐藏回调
const visibleChange = (visible: boolean) => {
  console.log('visibleChange', visible)
  console.log('visibleChange.defaultValue', defaultValue.value)
  if (visible) {
    // props.currentPage = 1
    // this.currentPage = 1
    // this.keyword = null
    // this.formData = {}
    // this.getData()
  } else {
    // this.autoCurrentLabel()
    autoCurrentLabel()
  }
  // autoCurrentLabel()
}

//自动模拟options赋值
const autoCurrentLabel = async () => {
  await nextTick(() => {
    if (props.multiple) {
      selectRef.value.states.selectedLabel = ''
      selectRef.value.states.selected = defaultSelect.value?.map((item: any) => {
        return {
          currentLabel: item[props.props.label],
          value: item[props.props.value]
        }
      })
    } else {
      selectRef.value.states.selectedLabel = defaultSelect.value[props.props.label as any]
      selectRef.value.states.selected = {
        currentLabel: defaultSelect.value[props.props.label as any],
        value: defaultSelect.value[props.props.value as any]
      }
    }
  })
}

//表格勾选事件
const handleSelect = async (selection: any[], row: any) => {
  let isSelect = selection.length && selection.indexOf(row) !== -1
  // console.log('handleSelect:isSelect', isSelect)
  // console.log('handleSelect:selection', selection)
  // console.log('handleSelect:row', row)
  if (isSelect) {
    defaultSelect.value.push(row)
    defaultValue.value.push(row[props.props.value])
  } else {
    defaultSelect.value = defaultSelect.value.filter((item: any) => item[props.props.value] !== row[props.props.value])
    // defaultValue.value = defaultValue.value.filter((item: any) => item !== row[props.props.value])

    // defaultSelect.value.splice(
    //   defaultSelect.value.indexOf((item: any) => item[props.props.value] == row[props.props.value]),
    //   1
    // )
    defaultValue.value.splice(
      defaultValue.value.indexOf((item: any) => item == row[props.props.value]),
      1
    )
  }
  // console.log('handleSelect:defaultSelect', defaultSelect.value)
  await autoCurrentLabel()
  emit('update:modelValue', defaultValue.value)
  emit('change', defaultValue.value)
}

//表格全选事件
const handleSelectAll = async (selection: any[]) => {
  const isAllSelect = selection.length > 0
  if (isAllSelect) {
    selection.forEach((row: any) => {
      // const isHas = defaultValue.value.find((item: any) => item[props.props.value] == row[props.props.value])
      const isHas = defaultSelect.value.find((item: any) => item[props.props.value] == row[props.props.value])
      if (!isHas) {
        // defaultValue.value.push(row)
        defaultSelect.value.push(row)
        defaultValue.value.push(row[props.props.value])
      }
    })
  } else {
    props.tableData?.forEach((row: any) => {
      // const isHas = defaultValue.value.find((item: any) => item[props.props.value] == row[props.props.value])
      const isHas = defaultSelect.value.find((item: any) => item[props.props.value] == row[props.props.value])
      if (isHas) {
        // defaultValue.value.splice(
        //   defaultValue.value.findIndex((item: any) => item[props.props.value] == row[props.props.value]),
        //   1
        // )
        defaultSelect.value.splice(
          defaultSelect.value.findIndex((item: any) => item[props.props.value] == row[props.props.value]),
          1
        )
        defaultValue.value.splice(
          defaultValue.value.indexOf((item: any) => item == row[props.props.value]),
          1
        )
      }
    })
  }
  await autoCurrentLabel()
  emit('update:modelValue', defaultValue.value)
  emit('change', defaultValue.value)
}

const handleRowDblclick = (row: any) => {
  if (props.multiple) {
    //处理多选点击行
  } else {
    defaultSelect.value = row
    defaultValue.value = row[props.props.value]
    blur()
    // focus()
    autoCurrentLabel()
    emit('update:modelValue', defaultValue.value)
    emit('change', defaultValue.value)
  }
}
//tags删除后回调 (第一次是字符串，之后是对象？)
const removeTag = (tag: any) => {
  emit('update:modelValue', defaultValue.value)
  console.log('tag', tag)
  const row = findRowByKey(tag instanceof Object ? tag[props.props.value] : tag)
  tableRef.value.toggleRowSelection(row, false)
  defaultSelect.value.splice(
    defaultSelect.value.findIndex((item: any) => item[props.props.value] == row[props.props.value]),
    1
  )
  autoCurrentLabel()
}

//清空后的回调
const clear = () => {
  emit('update:modelValue', defaultValue.value)
  props.tableData?.forEach((item: any) => {
    tableRef.value.toggleRowSelection(item, false)
  })
  defaultSelect.value = []
}

// 关键值查询表格数据行
const findRowByKey = (value: any) => {
  return props.tableData?.find((item: any) => item[props.props.value] === value)
}

// 触发select隐藏
const blur = () => {
  selectRef.value.blur()
}
// 触发select显示
// const focus = () => {
//   selectRef.value.focus()
// }

//组件默认赋值
const setDefaultSelection = async () => {
  console.log('setDefaultSelection')
  await nextTick(() => {
    defaultValue.value = props.modelValue
    if (props.multiple) {
      defaultValue.value.forEach((row: any) => {
        // const setRow: any = props.tableData?.filter((item: any) => item[props.props.value] === row[props.props.value])
        const setRow: any = props.tableData?.filter((item: any) => item[props.props.value] === row)
        console.log('multiple-setRow', setRow)
        if (setRow.length > 0) {
          setRow.forEach((item: any) => {
            tableRef.value.toggleRowSelection(item, true)
            defaultSelect.value.push(item)
          })
        }
      })
    } else {
      const setRow: any = props.tableData?.filter((item: any) => item[props.props.value] === defaultValue.value)
      console.log('only-setRow', setRow)
      if (setRow.length > 0) {
        tableRef.value.setCurrentRow(setRow[0])
        // defaultSelect.value.push(setRow[0])
        defaultSelect.value = setRow[0]
      }
    }
    tableRef.value.setScrollTop(0)
  })
  autoCurrentLabel()
}
defineExpose({ setDefaultSelection })
</script>

<template>
  <el-select
    ref="selectRef"
    v-model="defaultValue"
    :size="size"
    :clearable="clearable"
    :multiple="multiple"
    :collapse-tags="collapseTags"
    :collapse-tags-tooltip="collapseTagsTooltip"
    :filterable="filterable"
    :placeholder="placeholder"
    :disabled="disabled"
    @remove-tag="removeTag"
    @visible-change="visibleChange"
    @clear="clear"
    popper-class="vip-table-select-popper"
  >
    <template #empty>
      <div
        class="vip-table-select__table"
        :style="{ width: tableWidth ? `${tableWidth}px` : '100%' }"
        v-loading="loading"
      >
        <div class="vip-table-select__header">
          <slot name="header"></slot>
        </div>

        <el-table
          ref="tableRef"
          :data="tableData"
          :height="tableHeight ? tableHeight : 220"
          :border="border"
          :highlight-current-row="!multiple"
          @rowDblclick="handleRowDblclick"
          @select="handleSelect"
          @select-all="handleSelectAll"
        >
          <el-table-column v-if="multiple" type="selection" width="50"></el-table-column>
          <!--          <el-table-column type="index" label="序号" width="55" align="center" />-->
          <el-table-column type="index" label="序号" width="55">
            <template #default="scope">
              <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <slot></slot>
        </el-table>

        <div class="vip-table-select__footer" v-if="pagination">
          <el-pagination
            :page-size="pageSize"
            :total="total"
            background
            layout="prev, pager, next"
            size="small"
            @current-change="onCurrentChange"
            v-bind="$attrs"
          />
        </div>
      </div>
    </template>
  </el-select>
</template>

<style lang="scss">
.vip-table-select-popper {
  .el-select-dropdown__empty {
    text-align: unset !important;
  }
}
</style>

<style scoped lang="scss">
.vip-table-select__table {
  //padding: 12px;
  padding: 0 12px;
}

//.vip-table-select__header {
//}
//
//.vip-table-select__footer {
//}
</style>
